package com.web.base.user.service;

import com.blue.core.dict.Auth;
import com.blue.core.dict.Result;
import com.blue.jdbc.JdbcDataSource;
import com.blue.jdbc.Page;
import com.web.base.auth.dao.RoleUserDao;
import com.web.base.user.dao.UserDao;
import com.web.base.user.dao.UserLoginLogDao;
import com.web.base.user.dao.UserWechatDao;
import com.web.base.user.exception.UserException;
import com.web.base.user.model.User;
import com.web.core.util.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户业务层
 * 
 * @author 代码由 blue-code 框架生成
 * @since 1.0 2017年04月16日
 */
@Service
@Transactional
@JdbcDataSource(Const.DS_BASE)
public class UserService
{
	@Autowired
	private UserDao userDao;
	@Resource
	private UserLoginLogDao userLoginLogDao;
	@Autowired
	private RoleUserDao roleUserDao;
	@Autowired
	private UserWechatDao userWechatDao;
	
	public UserService()
	{
	}
	
	public User reg(User user, Integer appId, String ip, String wechatCode)
	{
		this.check(user);
		
		Date now = new Date();
		user.setCreateTime(now);
		user.setLoginTime(now);
		userDao.save(user);
		
		userLoginLogDao.add(appId, user.getId(), "注册并登录成功", Result.SUCCESS, ip);
		if (user.getWechatId() != null && user.getWxOpenId() != null && !user.getWxOpenId().isEmpty())
		{
			userWechatDao.update(user.getWechatId(), user.getId(), user.getWxOpenId(), wechatCode);
		}
		/*UserInfo userInfo = new UserInfo();
		userInfo.setId(user.getId());
		userInfoDao.save(userInfo);*/

		User a = userDao.get(user.getId());
		return a;
	}
	
	public User save(User user)
	{
		this.check(user);
		
		if (user.getId() == null)
		{
			Date now = new Date();
			user.setCreateTime(now);
			user.setLoginTime(now);
			userDao.save(user);
		}
		else
		{
			userDao.update(user);
		}
		User a = userDao.get(user.getId());
		return a;
	}

	public boolean isMobileExist(String mobile)
	{
		if (mobile == null || mobile.isEmpty())
			return false;

		int n = userDao.count("mobile", mobile);
		return n > 0;
	}
	
	private void check(User user)
	{
		if (userDao.exist(user, "name"))
			throw new UserException("用户名已存在：" + user.getName());
		
		if (user.getMobile() != null && !user.getMobile().isEmpty() && userDao.exist(user, "mobile"))
			throw new UserException("手机号码已存在：" + user.getMobile());
		
		if (user.getEmail() != null && !user.getEmail().isEmpty() && userDao.exist(user, "email"))
			throw new UserException("电子邮箱已存在：" + user.getEmail());
	}
	
	public User login(User user, Integer appId, String ip, String wechatCode)
	{
		User u = userDao.login(user);
		if (u == null)
			throw new UserException("用户登录失败");
		
		if (u.getAuth() == Auth.PENDING)
			throw new UserException("用户未审核，不能登录");
		if (u.getAuth() == Auth.UNAPPROVE)
			throw new UserException("用户审核不通过，禁止登录");
		if (u.getAuth() != Auth.APPROVE)
			throw new UserException("用户禁止登录");
		
		u.setLoginTime(new Date());
		userDao.update(u);
		
		userLoginLogDao.add(appId, u.getId(), "登录成功", Result.SUCCESS, ip);

		if (user.getWechatId() != null && user.getWxOpenId() != null && !user.getWxOpenId().isEmpty())
		{
			userWechatDao.update(user.getWechatId(), user.getId(), user.getWxOpenId(), wechatCode);
		}
		
		return u;
	}

	public User loginWechat(String wxOpenId, String wxUnionId, Integer wechatId, String ip)
	{
		if (wxUnionId != null && !wxUnionId.isEmpty())
		{
			User user = userDao.getObject("wxUnionId", wxUnionId);
			if (user != null)
			{
				userLoginLogDao.add(wechatId, user.getId(), "微信授权登录成功", Result.SUCCESS, ip);
				return user;
			}
		}
		if (wxOpenId != null && !wxOpenId.isEmpty())
		{
			User user = userWechatDao.loginByOpenId(wechatId, wxOpenId);
			if (user != null)
			{
				userLoginLogDao.add(wechatId, user.getId(), "微信授权登录成功", Result.SUCCESS, ip);
				return user;
			}
		}

		return null;
	}
	
	public User get(Integer id)
	{
		User log = userDao.get(id);
		return log;
	}

	public Map<Integer, User> getList(List<Integer> idList)
	{
		Map<Integer, User> map = userDao.getList(idList);
		return map;
	}
	
	public Page<User> list(User user, Page<User> page)
	{
		page = userDao.list(user, page);
		List<Integer> idList = page.getObjectList().stream().map(User::getId).collect(Collectors.toList());
		if (idList.isEmpty())
			return page;

		List<User> userRoleList = roleUserDao.groupRole(idList);
		Map<Integer, String> userRoleMap = new HashMap<>();
		userRoleList.forEach(e -> userRoleMap.put(e.getId(), e.getRoleNames()));
		for (User u : page.getObjectList())
		{
			u.setRoleNames(userRoleMap.get(u.getId()));
		}
		return page;
	}
	
	public void delete(User user)
	{
		userDao.delete(user);
	}
	
}
